package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author likepei
 * @Date 2020/2/5 14:31
 * @Version v1.0
 * @Description 用户操作的控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    //依赖注入, 通过Dubbo的远程调用, 把Zookeeper中的UserService实现类对象进行 赋值userService
    @Reference
    private UserService userService;

    /**
     * 获取用户名
     * @return
     */
    @RequestMapping("/getUsername")
    public Result getUsername(){
        try {
            //从授权框架上下文对象中 获取认证对象
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //再从 认证对象中 获取授权框架用户对象User
            User user = (User)authentication.getPrincipal();
            //用户对象User 获取 用户名
            String username = user.getUsername();
            //获取成功, 返回成功信息, 并返回用户名
            return new Result(true, MessageConst.ACTION_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            //获取失败,返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 登录成功
     * @return
     */
    @RequestMapping("/loginSuccess")
    public Result loginSuccess(){
        return new Result(true,MessageConst.LOGIN_SUCCESS);
    }

    /**
     * 登录失败
     * @return
     */
    @RequestMapping("/loginFail")
    public Result loginFail(){
        return new Result(false,"登录失败");
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public Result login(String username, String password){
        //打印日志, 获取浏览器发来的数据
        log.debug("UserController login......u={}...p={}", username, password);

        //调用service层的方法, 完成用户登录操作
        if (userService.login(username, password)){
            log.debug("login success");
            return new Result(true, MessageConst.ACTION_SUCCESS);
        } else {
            log.debug("login fail");
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
